package site.jlopen.utils;

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang3.time.DateFormatUtils;

/**
 * 时间工具类
 *
 * @author 码农小鹿
 */
public class DateUtil extends org.apache.commons.lang3.time.DateUtils {
	public static String YYYY = "yyyy";

	public static String YYYY_MM = "yyyy-MM";

	public static String YYYY_MM_DD = "yyyy-MM-dd";

	public static String HH_mm_ss = "HH:mm:ss";

	public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

	public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
	public static String YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm";

	private static String[] parsePatterns = { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
			"yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM", "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss",
			"yyyy.MM.dd HH:mm", "yyyy.MM" };

	public static final String CRON_DATE="ss mm HH dd MM ? yyyy";//ss mm HH dd MM ? *

	/**
	 * 获取当前Date型日期
	 *
	 * @return Date() 当前日期
	 */
	public static Date getNowDate() {
		return new Date();
	}

	/**
	 * 获取当前日期, 默认格式为yyyy-MM-dd
	 *
	 * @return String
	 */
	public static String getDate() {
		return dateTimeNow(YYYY_MM_DD);
	}

	public static final String getTime() {
		return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
	}

	public static final String dateTimeNow() {
		return dateTimeNow(YYYYMMDDHHMMSS);
	}

	/**
	 * 获取当前时间n小时之后的时间
	 * @remark 当前这个方法主要用于微信支付的订单超时时间
	 */
	public static final Date dateTimeNowAfterHour(Date date, int hour) {
		if(null == date) {
			date = new Date();
		}
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.HOUR_OF_DAY, hour);
		return calendar.getTime();
	}

	public static final Date dateTimeNowAfterYear(Date date, int year) {
		if(null == date) {
			date = new Date();
		}
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.YEAR, year);
		return calendar.getTime();
	}

	public static final Date dateTimeNowAfterMin(Date date, int minutes ) {
		if(null == date) {
			date = new Date();
		}
		Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MINUTE, minutes);
		return calendar.getTime();
	}

	public static final Date dateTimeSubtractMonth(Date date, int month ) {
		if(null == date) {
			date = new Date();
		}
		Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, -month);
		return calendar.getTime();
	}

	public static final String dateTimeNow(final String format) {
		return parseDateToStr(format, new Date());
	}

	public static final String dateTime(final Date date) {
		return parseDateToStr(YYYY_MM_DD, date);
	}

	public static final String parseDateToStr(final String format, final Date date) {
		return new SimpleDateFormat(format).format(date);
	}

	public static final Date dateTime(final String format, final String ts) {
		try {
			return new SimpleDateFormat(format).parse(ts);
		} catch (ParseException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 日期路径 即年/月/日 如2018/08/08
	 */
	public static final String datePath() {
		Date now = new Date();
		return DateFormatUtils.format(now, "yyyy/MM/dd");
	}

	/**
	 * 日期路径 即年/月/日 如20180808
	 */
	public static final String dateTime() {
		Date now = new Date();
		return DateFormatUtils.format(now, "yyyyMMdd");
	}

	/**
	 * 日期型字符串转化为日期 格式
	 */
	public static Date parseDate(Object str) {
		if (str == null) {
			return null;
		}
		try {
			return parseDate(str.toString(), parsePatterns);
		} catch (ParseException e) {
			return null;
		}
	}

	/**
	 * 获取服务器启动时间
	 */
	public static Date getServerStartDate() {
		long time = ManagementFactory.getRuntimeMXBean().getStartTime();
		return new Date(time);
	}

	/**
	 * 计算相差天数
	 */
	public static int differentDaysByMillisecond(Date date1, Date date2) {
		return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)));
	}

	/**
	 * 计算时间差
	 *
	 * @param endDate   最后时间
	 * @param startTime 开始时间
	 * @return 时间差（天/小时/分钟）
	 */
	public static String timeDistance(Date endDate, Date startTime) {
		long nd = 1000 * 24 * 60 * 60;
		long nh = 1000 * 60 * 60;
		long nm = 1000 * 60;
		// long ns = 1000;
		// 获得两个时间的毫秒时间差异
		long diff = endDate.getTime() - startTime.getTime();
		// 计算差多少天
		long day = diff / nd;
		// 计算差多少小时
		long hour = diff % nd / nh;
		// 计算差多少分钟
		long min = diff % nd % nh / nm;
		// 计算差多少秒//输出结果
		// long sec = diff % nd % nh % nm / ns;
		return day + "天" + hour + "小时" + min + "分钟";
	}
	/**
	 *
	* <strong>计算两个时间差</strong>
	* 前大后小
	* @Param type == 1 秒，2：分，3：小时，4天，5：年
	 */
	public static long timeDistance(Date endDate, Date startTime, int type) {
		// 获取两个日期的年月日
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(startTime);
        int year1 = calendar1.get(Calendar.YEAR);
        int month1 = calendar1.get(Calendar.MONTH) + 1;
        int day1 = calendar1.get(Calendar.DAY_OF_MONTH);

        Calendar calendar2 = Calendar.getInstance();
        calendar2.setTime(endDate);
        int year2 = calendar2.get(Calendar.YEAR);
        int month2 = calendar2.get(Calendar.MONTH) + 1;
        int day2 = calendar2.get(Calendar.DAY_OF_MONTH);
		// 获得两个时间的毫秒时间差异
		long diff = endDate.getTime() - startTime.getTime();
		switch (type) {
		case 1:
			long sec = diff / (1000);
			return sec;
		case 2:
			long min = diff / (1000 * 60);
			return min;
		case 3:
			long hour = diff / (1000 * 60 * 60);
			return hour;
		case 4:
			long day = diff / (1000 * 60 * 60 * 24);
			return day;
		case 5:
	        int months = (year2 - year1) * 12 + (month2 - month1);
	        if (day2 < day1) {
	            months -= 1;
	        }
			return months;
		case 6:
	        long year = (diff / (1000 * 60 * 60 * 24 * 365));
			return year;
		default:
			return 0;
		}
	}

	/**
	 * 增加 LocalDateTime ==> Date
	 */
	public static Date toDate(LocalDateTime temporalAccessor) {
		ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
		return Date.from(zdt.toInstant());
	}

	/**
	 * 增加 LocalDate ==> Date
	 */
	public static Date toDate(LocalDate temporalAccessor) {
		LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
		ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
		return Date.from(zdt.toInstant());
	}

	/**
	 * 两个时间比较
	 *
	 * @param date
	 * @return 相等返回0，大于返回1，小于返回-1.
	 */
	public static int compareDateWithNow(Date date) {
		return date.compareTo(new Date());
	}
	public static int compareDateWithNow(Date startDate,Date endDate) {
		return startDate.compareTo(endDate);
	}

	public static String getCron(String dtStr) {
		try {
			SimpleDateFormat java_date = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
			Date date1 =  java_date.parse(dtStr);
			SimpleDateFormat cron_date = new SimpleDateFormat(CRON_DATE);
			String cronStr = cron_date.format(date1);
			return cronStr;
		} catch (ParseException e) {
		}
		return null;
	}

	public static void main(String[] args) {
		Date date1 = new Date();
        Date date2 = new Date(2024, 1, 17, 13, 49, 1);
		System.out.println(timeDistance(date2, date1, 5));
	}
}
